#include "map.hh"

#include <tools/utility.hh>

Map::Map (int height, int width)
{
  height_ = height;
  width_ = width;

  map_ = new int*[height];
  for (int i = 0; i < height; ++i)
    {
      map_[i] = new int[width];
      for (int j = 0; j < width; ++j)
	map_[i][j] = 0;
    }
}

Map::~Map ()
{
  for (int i = 0; i < height_; ++i)
    delete[] map_[i];

  delete[] map_;
}

int
Map::operator() (int x, int y)
{
  return map_[x][y];
}

void
Map::operator() (int x, int y, int val)
{
  map_[x][y] = val;
}

int
Map::height_get ()
{
  return height_;
}

int
Map::width_get ()
{
  return width_;
}

#include <cstdlib>

std::list<Vector3d*>*
Map::points_calc (int offset_i, int offset_j)
{
  std::list<Vector3d*>* res = new std::list<Vector3d*>;
  int max = 0;
  int min = 0;

  int max_x = 0;
  int max_y = 0;

  if (offset_j == height_ - 256)
    max_y = height_ - 1;
  else
    max_y = offset_j + 256;

  if (offset_i == width_ - 256)
    max_x = width_ - 1;
  else
    max_x = offset_i + 256;

  for (int i = offset_i; i < max_x; ++i)
    for (int j = offset_j; j < max_y; ++j)
      {
	if (map_[i + 1][j] > map_[i + 1][j + 1])
	  {
	    max = map_[i + 1][j];
	    min = map_[i + 1][j + 1];
	  }
	else
	  {
	    min = map_[i + 1][j];
	    max = map_[i + 1][j + 1];
	  }

	if (max < map_[i][j + 1])
	  max = map_[i][j + 1];
	else if (min > map_[i][j + 1])
	  min = map_[i][j + 1];

	for (int x = max - 1; x > map_[i][j]; --x)
	  res->push_back (new Vector3d (i, j, x));

	for (int x = min + 1; x < map_[i][j]; ++x)
	  res->push_back (new Vector3d (i, j, x));
      }

  return res;
}

std::string
Map::tonet () const
{
  char size[4];
  Utility::to_oct (width_, size);

  return std::string (size, 4);
}
